/**
 * 购买单次票
 */
package com.kerrykidz.membership.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.kerrykidz.common.Constants;
import com.kerrykidz.common.ORDER_CONSTANTS;
import com.kerrykidz.common.service.ICommonService;
import com.kerrykidz.dao.model.GblPosDiscountEntity;
import com.kerrykidz.filemanagement.service.ISalesService;
import com.kerrykidz.filemanagement.service.IVipService;
import com.kerrykidz.membership.dao.model.CusGuaEntity;
import com.kerrykidz.membership.dao.model.CusMemEntity;
import com.kerrykidz.membership.dao.model.GblCusCReltypeEntity;
import com.kerrykidz.membership.service.IGuaService;
import com.kerrykidz.membership.service.IMemberService;
import com.kerrykidz.membership.service.ISingleService;
import com.kerrykidz.sales.dao.model.PosOrderEntity;
import com.kerrykidz.sales.dao.model.PosOrderPrdEntity;
import com.kerrykidz.sales.service.IOrderService;
import com.kerrykidz.sales.service.IPaymentService;
import com.kerrykidz.scminvoicing.dao.model.GblScmPrdEntity;
import com.kerrykidz.scminvoicing.service.IScmInvocingProductInfoService;
import com.kerrykidz.system.dao.model.GblCusCCountryEntity;
import com.kerrykidz.system.dao.model.SecUsrEntity;
import com.kerrykidz.system.service.IGblService;
import com.kerrykidz.system.service.IUserService;
import com.kerrykidz.system.util.DateUtil;
import com.kerrykidz.system.util.UserUtil;
import com.kerrykidz.system.util.createWord.CreateWD2003Util;
import com.kerrykidz.system.util.createWord.model.MMHeTongwordModel;
import com.kerrykidz.system.vo.UserInfo;
import com.rdp.framework.exception.RDPException;
import com.rdp.util.GenerationUUID;
import com.rdp.util.config.PropertiesUtil;

/**
 * @author Tik
 *
 */
@RequestMapping("membership/member")
@Controller
public class MemberController {

	@Autowired
	private ICommonService commonService;
	@Autowired
	private ISingleService singleService;
	@Autowired
	private IMemberService memberService;
	@Autowired
	private IGuaService guaService;
	@Autowired
	private IScmInvocingProductInfoService productService;
	@Autowired
	private IOrderService orderService;
	@Autowired
	private IPaymentService paymentService;
	@Autowired
	private IVipService vipService;
	@Autowired
	private ISalesService salesService;
	@Autowired
	private IUserService userService;
	@Autowired
	private IGblService gblService;

	
	
	/**
	 * 跳转到会员查询界面
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/jumpMember")
	public String jumpMember() throws RDPException {
		
		return "membership/membership_member";
	}
	
	/**
	 * 保存会员
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/saveMember")
	@ResponseBody
	public Map<String, String> saveMember(CusMemEntity member) throws RDPException {
		Map<String, String> map = new HashMap<String, String>();
		UserInfo user = UserUtil.getUserFromSession();
		member.setFkBranId(user.getBranId());
		member.setModiBy(user.getUserId());
		if (StringUtils.isBlank(member.getPkMemId())) {
			if (memberService.checkFingerprintExist(member.getFing1()) != 0 || memberService.checkFingerprintExist(member.getFing2()) != 0) {
				map.put("result", Constants.FAILURE);
				map.put("message", "指纹已存在于其它用户，不可重复创建！");
				return map;
			}
			member.setStatus(Constants.MEMBER_STATUS_CREATE);
			if (StringUtils.isBlank(member.getFamilyId())) {
				String familyId = GenerationUUID.getGenerationUUID();
				member.setFamilyId(familyId);
				map.put("familyId", familyId);
			}
			vipService.createVip(member);
			map.put("memberId", member.getPkMemId());
		} else {
			vipService.updateVip(member);
			map.put("memberId", member.getPkMemId());
		}
		map.put("result", Constants.SUCCESS);
		return map;
	}
	
	/**
	 * 保存监护人
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/saveGua")
	@ResponseBody
	public Map<String, String> saveGua(CusGuaEntity gua) throws RDPException {
		Map<String, String> map = new HashMap<String, String>();
		UserInfo user = UserUtil.getUserFromSession();
		gua.setFkBranId(user.getBranId());
		gua.setModiBy(user.getUserId());
		if (StringUtils.isBlank(gua.getPkGuaId())) {
			if (memberService.checkFingerprintExist(gua.getFing1()) != 0 || memberService.checkFingerprintExist(gua.getFing2()) != 0) {
				map.put("result", Constants.FAILURE);
				map.put("message", "指纹已存在于其它用户，不可重复创建！");
				return map;
			}
			vipService.createGuardian(gua);
		} else {
			vipService.updateGuardian(gua);
		}
		map.put("result", Constants.SUCCESS);
		return map;
	}
	
	/**
	 * 删除会员
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/deleteMember")
	@ResponseBody
	public String deleteMember(String memberId) throws RDPException {
		CusMemEntity member = new CusMemEntity();
		member.setPkMemId(memberId);
		UserInfo user = UserUtil.getUserFromSession();
		member.setModiBy(user.getUserId());
		memberService.deleteMember(member);
		return Constants.SUCCESS;
	}
	
	/**
	 * 删除监护人
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/deleteGua")
	@ResponseBody
	public String deleteGua(String guaId) throws RDPException {
		CusGuaEntity gua = new CusGuaEntity();
		gua.setPkGuaId(guaId);
		UserInfo user = UserUtil.getUserFromSession();
		gua.setModiBy(user.getUserId());
		guaService.deleteGua(gua);
		return Constants.SUCCESS;
	}
	
	/**
	 * 根据姓名或电话号码查询会员
	 * @return
	 * @throws RDPException
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/queryMember")
	@ResponseBody
	public List<CusMemEntity> queryMember(@RequestParam(value="nameOrTel")String nameOrTel) throws RDPException, UnsupportedEncodingException {
		nameOrTel = URLDecoder.decode(nameOrTel,"UTF-8");
		List<CusMemEntity> list = memberService.findMemberByNameOrTel(nameOrTel);
		return list;
		
	}
	
	/**
	 * 根据指纹查询会员
	 * @return
	 * @throws RDPException
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/queryMemberByFingerprint")
	@ResponseBody
	public CusMemEntity queryMemberByFingerprint(@RequestParam(value="fingerprint")String fingerprint) throws RDPException {
		Object obj = memberService.findFingerprint(fingerprint);
		if (obj instanceof CusMemEntity) {
			CusMemEntity mem = (CusMemEntity)obj;
			return mem;
		}
		return null;
		
	}
	
	/**
	 * 根据会员编号查询会员
	 * @return
	 * @throws RDPException
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/queryMemberById")
	@ResponseBody
	public CusMemEntity queryMemberById(@RequestParam(value="memberId")String memberId) throws RDPException {
		CusMemEntity member = memberService.findMemberById(memberId);
		return member;
		
	}
	
	/**
	 * 根据监护人编号查询监护人
	 * @return
	 * @throws RDPException
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/queryGuaById")
	@ResponseBody
	public CusGuaEntity queryGuaById(@RequestParam(value="guaId")String guaId) throws RDPException {
		CusGuaEntity gua = guaService.findGuaById(guaId);
		return gua;
		
	}

	
	/**
	 * 查询会员及其关联信息
	 * @param memberId	会员编号
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/queryMemberDetail")
	public ModelAndView queryMemberDetail(@RequestParam(value="memberId",required=false)String memberId, @RequestParam(value="type",required=false)String type) throws RDPException {

		ModelAndView mv = new ModelAndView("membership/membership_member_detail");

		if (StringUtils.isNotBlank(memberId)) {
			//会员、非会员信息 兄弟姐妹
			List<CusMemEntity> memList = memberService.findMemberAndSiblingsById(memberId);
			mv.addObject("memList", memList);
			if (memList.size() > 0) {
				mv.addObject("familyId", memList.get(0).getFamilyId());
			}
			mv.addObject("memberId", memberId);
			mv.addObject("type", type);
			
			//监护人列表
			List<CusGuaEntity> guaList = memberService.findGuaByMemberId(memberId);
			mv.addObject("guaList", guaList);
			
		}
		
		List<GblCusCReltypeEntity> reltypeList = memberService.findReltypes();
		mv.addObject("reltypeList", reltypeList);
		
		//会籍商品列表
		UserInfo user = UserUtil.getUserFromSession();
		GblScmPrdEntity  prdEntity = new GblScmPrdEntity();
		prdEntity.setResverseType(Constants.PRODUCT_TYPE_MEMBER);
		prdEntity.setFkBranId(user.getBranId());
		List<GblScmPrdEntity> productList = productService.getProductInfo(prdEntity);
		mv.addObject("productList", productList);
		
		//销售列表
		List<SecUsrEntity> salesList = userService.listUserByRoleId("106");
		mv.addObject("salesList", salesList);

		//国籍列表
		List<GblCusCCountryEntity> countryList = gblService.selectAll();
		mv.addObject("countryList", countryList);
		
		return mv;
		
	}
	
	/**
	 * 下单界面
	 * @return
	 * @throws RDPException 
	 */
	@RequestMapping("/findPayment")
	public ModelAndView findPayment(HttpSession session
					,@RequestParam(value="buyMemberId") String[] memberIds,
					@RequestParam(value="memName") String[] memNames,
					@RequestParam(value="buyMemberCardId") String[] buyMemberCardIds,
					@RequestParam(value="recharge", required=false) String[] recharges,
					@RequestParam(value="type") String type) throws RDPException {
		UserInfo user = UserUtil.getUserFromSession();
		GblScmPrdEntity  prdEntity = new GblScmPrdEntity();
		prdEntity.setResverseType(Constants.PRODUCT_TYPE_MEMBER);
		prdEntity.setFkBranId(user.getBranId());
		List<GblScmPrdEntity> productList = productService.getProductInfo(prdEntity);
		// 取得购买商品列表
		List<GblScmPrdEntity> prds = new ArrayList<GblScmPrdEntity>();
		for (GblScmPrdEntity prd : productList) {
			for (int i = 0; i < buyMemberCardIds.length; i++) {
				String CardId = buyMemberCardIds[i];
				if (StringUtils.isNotBlank(CardId) && CardId.equals(prd.getPkPrdId())) {
					prd.setQuantity(1);
					prd.setFkMemId(memberIds[i]);
					prd.setMemName(memNames[i]);
					
					if(null!=type && "1".equals(type)){
						//会员续会折扣（过期后一个月之内95折）
						CusMemEntity cusMem=memberService.findMemberById(memberIds[i]);
						if(null!=cusMem){
							if((null!=cusMem.getStatus() && "2".equals(cusMem.getStatus())) && (null!=cusMem.getMemType() && "1".equals(cusMem.getMemType()))){
								//会员有效期内充值也打95折
								toDisCount(prd);
							}else if(null!=cusMem.getEndDate() && null!=cusMem.getStatus() && !"3".equals(cusMem.getStatus()) && !"5".equals(cusMem.getStatus())){
								//有效期终止30天内打95折
								int days = DateUtil.getDiffDays(cusMem.getEndDate(), new Date());
								if(days<=30){
									toDisCount(prd);
								}
							}
							
						}
					}
					prds.add(prd);
				}
			}
		}

		ModelAndView mv = new ModelAndView("membership/membership_member_payment");

		if (prds.size() > 1) {
			mv.addObject("giftEnable", 0);
		}
		
		if(null!=recharges){
			for (int i = 0; i < recharges.length; i++) {
				if (StringUtils.isNotBlank(recharges[i]) && !"0".equals(recharges[i])) {
					GblScmPrdEntity rechargePrd = new GblScmPrdEntity();
					rechargePrd.setPrdName("充值");
					rechargePrd.setQuantity(Integer.parseInt(recharges[i]));
					rechargePrd.setProductPrice(1);
					rechargePrd.setFkMemId(memberIds[i]);
					rechargePrd.setMemName(memNames[i]);
					prds.add(rechargePrd);
				}
			}
		}
		mv.addObject("orderList", prds);
		
		List<GblPosDiscountEntity> discountList = productService.findAllDiscount();
		mv.addObject("discountList", discountList);
		
		GblScmPrdEntity entity = new GblScmPrdEntity();
		entity.setResverseType(Constants.PRODUCT_TYPE_GIFT);
		entity.setFkBranId(UserUtil.getUserFromSession().getBranId());
		List<GblScmPrdEntity> giftList = productService.getProductInfo(entity);
		mv.addObject("giftList", giftList);
		
		//记录跳转页面信息
		mv.addObject("type", type);
		
		return mv;
	}

	private void toDisCount(GblScmPrdEntity prd) {
		PropertiesUtil prop = new PropertiesUtil();
		String disDesc = prop.readSingleProps("RENEWAL_DISDESC", "/properties/kerrykidz.properties");
		String disCount = prop.readSingleProps("RENEWAL_DISCOUNT", "/properties/kerrykidz.properties");
		prd.setPkDisId("");
		prd.setDisValue(Double.parseDouble(disCount));
		prd.setDisDesc(disDesc);
	}
	
	/**
	 * 经理密码验证
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/validationManagerPassword")
	@ResponseBody
	public String validationManagerPassword(@RequestParam(value="password")String password) throws RDPException {
		SecUsrEntity user = commonService.findDiscountUser(password, UserUtil.getUserFromSession().getBranId());
		if (user != null) {
			return user.getPkUsrId();
		}
		return Constants.FAILURE;
	}
	
	/**
	 * 验证礼券
	 * @param giftNo 礼券号码
	 * @return
	 * @throws RDPException 
	 * @date: 2014年8月24日
	 */
	@RequestMapping(value = "/validationGiftNo")
	@ResponseBody
	public String validationGiftNo(String giftNo) throws RDPException {
		
		if (orderService.isUsedGiftno(giftNo)) {
			return Constants.SUCCESS;
		}
		return Constants.FAILURE;
	}
	
	/**
	 * 下单
	 * @param session
	 * @param memberId	会员编号
	 * @param pkPrdIds		商品编号
	 * @param pkDisId		折扣编号
	 * @param quantitys		数量
	 * @param productPrice	商品单价
	 * @param total			商品金额
	 * @param discountTotal	折后金额
	 * @param giftNos		优惠券编号
	 * @param amount		商品总额
	 * @return
	 * @throws Exception 
	 * @date: 2014年8月13日
	 */
	@RequestMapping("/placeOrder")
	@ResponseBody
	public String placeOrder(HttpSession session
					, @RequestParam(value="fkMemId") String[] fkMemIds
					, @RequestParam(value="pkPrdId") String[] pkPrdIds
					, @RequestParam(value="pkDisId") String[] pkDisIds
					, @RequestParam(value="fkUsrId") String[] fkUsrIds
					, @RequestParam(value="quantity") Integer[] quantitys
					, @RequestParam(value="price") Double[] prices
					, @RequestParam(value="discountTotal") Double[] discountTotals
					, @RequestParam(value="giftNos", required=false) String[] giftNos
					, @RequestParam(value="amount") Double amount) throws Exception {

		
		PosOrderEntity order = new PosOrderEntity();
		// 订单类型（会籍）
		order.setOrderType(ORDER_CONSTANTS.ORDER_TYPE_VIP);
		order.setRetFlag(ORDER_CONSTANTS.RET_FLAG_NO);
		// 订单状态
		order.setOrderStatus(ORDER_CONSTANTS.ORDER_STATUS_NOT_PAY);
		// 优惠券编号
		if (giftNos != null) {
			String gift = "";
			for (String giftNo : giftNos) {
				gift += "," + giftNo;
			}
			order.setGiftNo(gift + ",");
		}
		// 总金额
		order.setAmount(amount);
		UserInfo user = UserUtil.getUserFromSession();
		// 下单人，关联SEC_USR表
		order.setFkOperator(user.getUserId());
		// 分店编号，关联GBL_SEC_BRAN表
		order.setFkBranId(user.getBranId());
		order.setModiBy(UserUtil.getUserFromSession().getUserId());

		String cusName = "";
		List<PosOrderPrdEntity> productList = new ArrayList<PosOrderPrdEntity>();
		for (int i = 0; i < pkPrdIds.length; i++) {
			PosOrderPrdEntity product = new PosOrderPrdEntity();
			// 消费类型
			if  (StringUtils.isBlank(pkPrdIds[i])) {
				product.setType(ORDER_CONSTANTS.ORDER_PRD_TYPE_CHARGE);
			} else {
				product.setType(ORDER_CONSTANTS.ORDER_PRD_TYPE_PRODUCT);
				CusMemEntity mem = memberService.findMemberById(fkMemIds[i]);
				cusName += "/" + mem.getMemName();
			}
			// 商品编号
			product.setFkPrdId(pkPrdIds[i]);
			// 会籍或单次票订单关联的会员非会员编号
			product.setFkMemId(fkMemIds[i]);
			// 排序索引
			product.setOrdIndex(i);
			// 购买数量
			product.setCount(quantitys[i]);
			// 商品特殊折扣编号
			product.setFkDisId(pkDisIds.length == 0 ? null : pkDisIds[i]);
			// 商品特殊折扣授权编号
			product.setFkDisusrId(fkUsrIds.length == 0 ? null : fkUsrIds[i]);
			// 单价
			product.setPrice(prices[i]);
			// 折后单价
			product.setDisPrice(discountTotals[i]);
			// 订单使用的会员续会优惠券编号
			//product.setExtcpnFlag("0");
			
			productList.add(product);
		}
		order.setCusName(cusName.substring(1));
		String orderId = orderService.createHavePayOfOrder(order, productList, null,  UserUtil.getUserFromSession().getAbbrCode());
		return orderId;
	}
	
	
	/**
	 * 刷新付款结果
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/refreshPayResult")
	@ResponseBody
	public String refreshPayResult(String orderId) throws RDPException {
		boolean ispay = paymentService.isPay(orderId);
		return ispay ? Constants.SUCCESS : Constants.FAILURE;
	}

	
	/**
	 * 跳转到会员新建界面
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/CreateMemberContack")
	public void createMemberContack(HttpServletResponse response) throws RDPException {
		
		try{
		MMHeTongwordModel mmModel =new MMHeTongwordModel("TJHY1410270002","王小于","男","5","2005-02-02",
				    "中国香港", "王大志", "18888888888", "02188888888", "23@www.como", "北京地铁站附加的总公司是立交桥23号111111弄11楼到底哪里");
		String pathFile = CreateWD2003Util.createMemberWord(mmModel);//根据 word模版，生成word2003 文件
		File fil = new File(pathFile);
		if (fil.exists()) {
		response.addHeader("Content-Disposition", "attachment;filename=\""
				+ URLEncoder.encode("会员合同", "UTF-8")+"\"");
		//response.addHeader("Content-Length", "" + fil.length() + "");
		response.setContentType("application/x-download");

		byte[] buffer = new byte[4096];// 缓冲区
		BufferedOutputStream output = null;
		BufferedInputStream input = null;
		try {
			output = new BufferedOutputStream(response.getOutputStream());
			input = new BufferedInputStream(new FileInputStream(fil));
			int n = -1;
			while ((n = input.read(buffer, 0, 4096)) > -1) {
				output.write(buffer, 0, n);
			}
			output.flush();
			response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 关闭流
			if (input != null)
				input.close();
			if (output != null)
				output.close();
		} 
		}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	
	/**
	 * 跳转到会员新建界面
	 * @return
	 * @throws RDPException
	 */
	@RequestMapping("/jumpMemberPad")
	public String jumpMemberPad() throws RDPException {
		
		return "pad/ipad_mship/detail";
	}
	
}
